'use client';

import React, { useState, useEffect, useCallback } from 'react';
import {
  PageHeader,
  StatusBadge,
  Card,
  Button,
  InputGroup,
} from '@/components/common';

import { sha256 } from '@/utils/crypto';

import { YINDENG_SIDECHAIN_URL, YINDENG_MAINCHAIN_URL } from '@/utils/config';

const SIDE_CHAIN_URL = YINDENG_SIDECHAIN_URL;
const MAIN_CHAIN_URL = YINDENG_MAINCHAIN_URL;
const CHAIN_ID = "chain1"

// 类型定义
interface EvidenceSubmitRequest {
  dataHash: string;
  evidenceData: string;
  evidenceID: string;
}

interface SideLockRequest {
  clientID: string;
  seed: number;
  timeout: number;
  dataHash: string;
  evidenceID: string;
  chainID: string;
}

interface MainLockRequest {
  hashValue: string;
  clientID: string;
  timeout: number;
  dataHash: string;
  evidenceData: string;
  evidenceID: string;
  sidechainChainID: string;
}

interface UnlockRequest {
  lockKey: string;
  preimage: string;
}

interface SyncRequest {
  evidenceID: string;
}

interface EvidenceInfo {
  AdditionalInfo?: Record<string, unknown>;
  ChainID: string;
  CreateTime: number;
  DataHash: string;
  EvidenceData: string;
  EvidenceID: string;
  Status: string;
  UpdateTime: number;
}

export default function YindengEvidenceAnchorPage() {
  const [sidechainRunning, setSidechainRunning] = useState<boolean | null>(null);
  const [mainchainRunning, setMainchainRunning] = useState<boolean | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);
  const [logs, setLogs] = useState<string[]>([]);
  const [evidences, setEvidences] = useState<EvidenceInfo[]>([]);
  
  // 流程数据状态
  const [evidenceData, setEvidenceData] = useState<string>(JSON.stringify({
    registryType: '信贷资产登记',
    assetID: 'ASSET2024001',
    principalAmount: 5000000,
    interestRate: 0.045,
    maturityDate: '2025-12-31',
    registrationDate: new Date().toISOString().split('T')[0],
    borrowerID: 'BORROWER001',
    registrationCode: 'YD-REG-2024-001'
  }, null, 2));

  const [dataHash, setDataHash] = useState<string>('');
  const [evidenceID, setEvidenceID] = useState<string>('11205');
  const [clientID, setClientID] = useState<string>('clientA');
  const [preimage, setPreimage] = useState<string>('123456789');
  const [seed, setSeed] = useState<number>(123456789);
  const [lockHash, setLockHash] = useState<string>('');
  const [lockKey, setLockKey] = useState<string>('');

  // 添加日志
  const addLog = (message: string) => {
    setLogs(prev => [...prev, `${new Date().toLocaleTimeString()}: ${message}`]);
  };

  // 计算哈希 - 使用Web Crypto API进行真正的SHA256计算
  const calculateHash = async (data: string): Promise<string> => {
    try {
      const hashBuffer = await sha256(data);
      // const hashBuffer = await crypto.subtle.digest('SHA-256', bytes);
      const hashArray = Array.from(new Uint8Array(hashBuffer));
      const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
      return hashHex;
    } catch (error) {
      console.error('哈希计算失败:', error);
      // 如果Web Crypto API不可用，使用简单的fallback方法
      const encoder = new TextEncoder();
      const bytes = encoder.encode(data);
      const hashArray = Array.from(bytes);
      const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
      // 对结果再进行一次处理，模拟SHA256的长度
      const repeatedHash = (hashHex + hashHex + hashHex + hashHex).slice(0, 64);
      return repeatedHash;
    }
  };

  // 验证哈希是否正确 - 用于调试
  const verifyHash = async (data: string, expectedHash?: string) => {
    const calculatedHash = await calculateHash(data);
    addLog(`数据长度: ${data.length} 字节`);
    addLog(`计算哈希: ${calculatedHash}`);
    if (expectedHash) {
      addLog(`期望哈希: ${expectedHash}`);
      addLog(`哈希匹配: ${calculatedHash === expectedHash ? '是' : '否'}`);
    }
    return calculatedHash;
  };

  // 检查服务器状态
  const checkServers = useCallback(async () => {
    try {
      addLog(`检查侧链状态: GET ${SIDE_CHAIN_URL}/evidence?chainId=${CHAIN_ID}&page=1&pageSize=10`);
      const sideResponse = await fetch(`${SIDE_CHAIN_URL}/evidence?chainId=${CHAIN_ID}&page=1&pageSize=10`);
      if (sideResponse.ok) {
        const sideResult = await sideResponse.json();
        addLog(`侧链状态响应: ${JSON.stringify(sideResult, null, 2)}`);
        setSidechainRunning(true);
      } else {
        addLog(`侧链状态检查失败: ${sideResponse.status} ${sideResponse.statusText}`);
        setSidechainRunning(false);
      }
    } catch (error) {
      console.error('侧链连接失败:', error);
      addLog(`侧链连接异常: ${error}`);
      setSidechainRunning(false);
    }

    try {
      addLog(`检查主链状态: GET ${MAIN_CHAIN_URL}/evidence?chainId=${CHAIN_ID}&page=1&pageSize=10`);
      const mainResponse = await fetch(`${MAIN_CHAIN_URL}/evidence?chainId=${CHAIN_ID}&page=1&pageSize=10`);
      if (mainResponse.ok) {
        const mainResult = await mainResponse.json();
        addLog(`主链状态响应: ${JSON.stringify(mainResult, null, 2)}`);
        setMainchainRunning(true);
      } else {
        addLog(`主链状态检查失败: ${mainResponse.status} ${mainResponse.statusText}`);
        setMainchainRunning(false);
      }
    } catch (error) {
      console.error('主链连接失败:', error);
      addLog(`主链连接异常: ${error}`);
      setMainchainRunning(false);
    }
  }, []);

  // 加载存证信息
  const loadEvidences = async () => {
    try {
      addLog(`加载存证信息: GET ${MAIN_CHAIN_URL}/evidence?chainId=${CHAIN_ID}&page=1&pageSize=10`);
      const mainResponse = await fetch(`${MAIN_CHAIN_URL}/evidence?chainId=${CHAIN_ID}&page=1&pageSize=10`);
      if (mainResponse.ok) {
        const result = await mainResponse.json();
        addLog(`存证信息响应: ${JSON.stringify(result, null, 2)}`);
        setEvidences(result.evidences || []);
      } else {
        addLog(`加载存证信息失败: ${mainResponse.status} ${mainResponse.statusText}`);
        setEvidences([]);
      }
    } catch (error) {
      console.error('获取存证信息失败:', error);
      addLog(`加载存证信息异常: ${error}`);
      setEvidences([]);
    }
  };

  // 添加客户端渲染标识
  const [isClient, setIsClient] = useState(false);

  useEffect(() => {
    // 确保只在客户端执行
    setIsClient(true);
    
    const initializeData = async () => {
      checkServers();
      loadEvidences();
      // 初始化时计算数据哈希
      const hash = await calculateHash(evidenceData);
      setDataHash(hash);
    };
    
    initializeData();
  }, []);

  
  // 步骤1：初始化账本
  const handleInitializeLedgers = async () => {
    setIsProcessing(true);
    addLog('开始初始化账本...');
    
    try {
      // 初始化侧链
      addLog(`请求侧链初始化: POST ${SIDE_CHAIN_URL}/evidence/initialize?chainId=${CHAIN_ID}`);
      addLog(`请求参数: 无body参数`);
      
      const sideResponse = await fetch(`${SIDE_CHAIN_URL}/evidence/initialize?chainId=${CHAIN_ID}`, {
        method: 'POST'
      });
      
      const sideResult = await sideResponse.json();
      addLog(`侧链响应: ${JSON.stringify(sideResult, null, 2)}`);
      
      // 初始化主链
      addLog(`请求主链初始化: POST ${MAIN_CHAIN_URL}/evidence/initialize?chainId=${CHAIN_ID}`);
      addLog(`请求参数: 无body参数`);
      
      const mainResponse = await fetch(`${MAIN_CHAIN_URL}/evidence/initialize?chainId=${CHAIN_ID}`, {
        method: 'POST'
      });

      const mainResult = await mainResponse.json();
      addLog(`主链响应: ${JSON.stringify(mainResult, null, 2)}`);

      if (sideResponse.ok && mainResponse.ok) {
        if (sideResult.success && mainResult.success) {
          addLog('侧链和主链账本初始化成功');
          setCurrentStep(1);
        } else {
          addLog('账本初始化失败');
        }
      } else {
        addLog('账本初始化请求失败');
      }
    } catch (error) {
      console.error('账本初始化失败:', error);
      addLog('账本初始化失败，请检查网络连接');
    } finally {
      setIsProcessing(false);
    }
  };

  // 步骤2：在侧链提交数据
  const handleSubmitDataToSidechain = async () => {
    setIsProcessing(true);
    addLog('在侧链提交数据...');
    
    try {
      // 重新计算并验证哈希
      const verifiedHash = await verifyHash(evidenceData);
      setDataHash(verifiedHash);
      
      const submitData: EvidenceSubmitRequest = {
        dataHash: verifiedHash,
        evidenceData: evidenceData,
        evidenceID: evidenceID
      };

      addLog(`请求侧链提交数据: POST ${SIDE_CHAIN_URL}/evidence/data/side?chainId=${CHAIN_ID}`);
      console.log(`请求侧链提交数据: POST ${SIDE_CHAIN_URL}/evidence/data/side?chainId=${CHAIN_ID}`);
      addLog(`请求参数: ${JSON.stringify(submitData, null, 2)}`);
      console.log(`请求参数: ${JSON.stringify(submitData, null, 2)}`);

      const response = await fetch(`${SIDE_CHAIN_URL}/evidence/data/side?chainId=${CHAIN_ID}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(submitData),
      });

      if (response.ok) {
        const result = await response.json();
        addLog(`响应数据: ${JSON.stringify(result, null, 2)}`);
        
        if (result.success) {
          addLog(`侧链数据提交成功！数据哈希: ${verifiedHash}`);
          setCurrentStep(2);
          await loadEvidences();
        } else {
          addLog('侧链数据提交失败');
        }
      } else {
        const errorText = await response.text();
        addLog(`请求失败响应: ${errorText}`);
        addLog('侧链数据提交请求失败');
      }
    } catch (error) {
      console.error('侧链数据提交失败:', error);
      addLog(`请求异常: ${error}`);
      addLog('侧链数据提交失败，请检查网络连接');
    } finally {
      setIsProcessing(false);
    }
  };

  // 步骤3：在侧链创建锁
  const handleCreateSidechainLock = async () => {
    setIsProcessing(true);
    addLog('在侧链创建锁...');
    
    try {
      const lockData: SideLockRequest = {
        clientID: clientID,
        seed: seed,
        timeout: 1000,
        dataHash: dataHash,
        evidenceID: evidenceID,
        chainID: CHAIN_ID
      };

      addLog(`请求侧链创建锁: POST ${SIDE_CHAIN_URL}/evidence/lock/side?chainId=${CHAIN_ID}`);
      addLog(`请求参数: ${JSON.stringify(lockData, null, 2)}`);

      const response = await fetch(`${SIDE_CHAIN_URL}/evidence/lock/side?chainId=${CHAIN_ID}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(lockData),
      });

      if (response.ok) {
        const result = await response.json();
        addLog(`响应数据: ${JSON.stringify(result, null, 2)}`);
        
        if (result.success && result.lockHash) {
          const newLockHash = result.lockHash;
          const newLockKey = `lock_${clientID}_${newLockHash}`;
          setLockHash(newLockHash);
          setLockKey(newLockKey);
          addLog(`侧链锁创建成功！Lock Hash: ${newLockHash}`);
          addLog(`Lock Key: ${newLockKey}`);
          setCurrentStep(3);
        } else {
          addLog('侧链锁创建失败');
        }
      } else {
        const errorText = await response.text();
        addLog(`请求失败响应: ${errorText}`);
        addLog('侧链锁创建请求失败');
      }
    } catch (error) {
      console.error('侧链锁创建失败:', error);
      addLog(`请求异常: ${error}`);
      addLog('侧链锁创建失败，请检查网络连接');
    } finally {
      setIsProcessing(false);
    }
  };

  // 步骤4：在主链创建锁
  const handleCreateMainchainLock = async () => {
    setIsProcessing(true);
    addLog('在主链创建锁...');
    
    try {
      // 再次验证哈希确保一致性
      const verifiedHash = await verifyHash(evidenceData, dataHash);
      
      const lockDataMain: MainLockRequest = {
        hashValue: lockHash,
        clientID: clientID,
        timeout: 300,
        dataHash: verifiedHash, // 使用验证后的哈希
        evidenceData: evidenceData,
        evidenceID: evidenceID,
        sidechainChainID: CHAIN_ID
      };
      
      addLog(`请求主链创建锁: POST ${MAIN_CHAIN_URL}/evidence/lock/main?chainId=${CHAIN_ID}`);
      addLog(`请求参数: ${JSON.stringify(lockDataMain, null, 2)}`);
      
      const response = await fetch(`${MAIN_CHAIN_URL}/evidence/lock/main?chainId=${CHAIN_ID}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(lockDataMain),
      });

      if (response.ok) {
        const result = await response.json();
        addLog(`响应数据: ${JSON.stringify(result, null, 2)}`);
        
        if (result.success) {
          addLog('主链锁创建成功！');
          setCurrentStep(4);
          await loadEvidences();
        } else {
          addLog('主链锁创建失败');
        }
      } else {
        const errorText = await response.text();
        addLog(`请求失败响应: ${errorText}`);
        addLog('主链锁创建请求失败');
      }
    } catch (error) {
      console.error('主链锁创建失败:', error);
      addLog(`请求异常: ${error}`);
      addLog('主链锁创建失败，请检查网络连接');
    } finally {
      setIsProcessing(false);
    }
  };

  // 步骤5：侧链解锁
  const handleUnlockSidechain = async () => {
    setIsProcessing(true);
    addLog('侧链解锁...');
    
    try {
      const unlockData: UnlockRequest = {
        lockKey: lockKey,
        preimage: preimage
      };

      addLog(`请求侧链解锁: POST ${SIDE_CHAIN_URL}/evidence/unlock/side?chainId=${CHAIN_ID}`);
      addLog(`请求参数: ${JSON.stringify(unlockData, null, 2)}`);

      const response = await fetch(`${SIDE_CHAIN_URL}/evidence/unlock/side?chainId=${CHAIN_ID}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(unlockData),
      });

      if (response.ok) {
        const result = await response.json();
        addLog(`响应数据: ${JSON.stringify(result, null, 2)}`);
        
        if (result.code === 0) {
          addLog(`侧链解锁成功：${result.message}`);
          setCurrentStep(5);
        } else {
          addLog('侧链解锁失败');
        }
      } else {
        const errorText = await response.text();
        addLog(`请求失败响应: ${errorText}`);
        addLog('侧链解锁请求失败');
      }
    } catch (error) {
      console.error('侧链解锁失败:', error);
      addLog(`请求异常: ${error}`);
      addLog('侧链解锁失败，请检查网络连接');
    } finally {
      setIsProcessing(false);
    }
  };

  // 步骤6：主链解锁
  const handleUnlockMainchain = async () => {
    setIsProcessing(true);
    addLog('主链解锁...');
    
    try {
      const unlockData: UnlockRequest = {
        lockKey: lockKey,
        preimage: preimage
      };

      addLog(`请求主链解锁: POST ${MAIN_CHAIN_URL}/evidence/unlock/main?chainId=${CHAIN_ID}`);
      addLog(`请求参数: ${JSON.stringify(unlockData, null, 2)}`);

      const response = await fetch(`${MAIN_CHAIN_URL}/evidence/unlock/main?chainId=${CHAIN_ID}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(unlockData),
      });

      if (response.ok) {
        const result = await response.json();
        addLog(`响应数据: ${JSON.stringify(result, null, 2)}`);
        
        if (result.code === 0) {
          addLog(`主链解锁成功：${result.message}`);
          setCurrentStep(6);
        } else {
          addLog('主链解锁失败');
        }
      } else {
        const errorText = await response.text();
        addLog(`请求失败响应: ${errorText}`);
        addLog('主链解锁请求失败');
      }
    } catch (error) {
      console.error('主链解锁失败:', error);
      addLog(`请求异常: ${error}`);
      addLog('主链解锁失败，请检查网络连接');
    } finally {
      setIsProcessing(false);
    }
  };

  // 步骤7：主链确认同步
  const handleConfirmSync = async () => {
    setIsProcessing(true);
    addLog('主链确认同步...');
    
    try {
      const syncData: SyncRequest = {
        evidenceID: evidenceID
      };

      addLog(`请求主链确认同步: POST ${MAIN_CHAIN_URL}/evidence/confirm-sync?chainId=${CHAIN_ID}`);
      addLog(`请求参数: ${JSON.stringify(syncData, null, 2)}`);

      const response = await fetch(`${MAIN_CHAIN_URL}/evidence/confirm-sync?chainId=${CHAIN_ID}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(syncData),
      });

      if (response.ok) {
        const result = await response.json();
        addLog(`响应数据: ${JSON.stringify(result, null, 2)}`);
        
        if (result.status) {
          addLog(`同步确认成功：${result.status}`);
          setCurrentStep(7);
          await loadEvidences();
        } else {
          addLog('同步确认失败');
        }
      } else {
        const errorText = await response.text();
        addLog(`请求失败响应: ${errorText}`);
        addLog('同步确认请求失败');
      }
    } catch (error) {
      console.error('同步确认失败:', error);
      addLog(`请求异常: ${error}`);
      addLog('同步确认失败，请检查网络连接');
    } finally {
      setIsProcessing(false);
    }
  };

  const steps = [
    { title: '初始化账本', description: '初始化侧链和主链账本', completed: currentStep > 0 },
    { title: '侧链提交数据', description: '在侧链提交银登数据', completed: currentStep > 1 },
    { title: '侧链创建锁', description: '在侧链创建哈希时间锁', completed: currentStep > 2 },
    { title: '主链创建锁', description: '在主链创建对应的锁', completed: currentStep > 3 },
    { title: '侧链解锁', description: '使用原像解锁侧链', completed: currentStep > 4 },
    { title: '主链解锁', description: '使用原像解锁主链', completed: currentStep > 5 },
    { title: '确认同步', description: '主链确认数据同步完成', completed: currentStep > 6 },
  ];

  const totalEvidences = evidences.length;

  // 防止服务端渲染不一致
  if (!isClient) {
    return (
      <div className="min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
        <PageHeader title="银登数据跨链存证演示" />
        <main className="flex flex-col gap-8 items-center w-full max-w-6xl mx-auto pt-20">
          <div className="text-center">加载中...</div>
        </main>
      </div>
    );
  }

  return (
    <div className="min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
      <PageHeader title="银登数据跨链存证演示" />

      <main className="flex flex-col gap-8 items-center w-full max-w-6xl mx-auto pt-20">
        
        {/* 服务器状态 */}
        <div className="w-full bg-gray-50 rounded-lg p-6">
          <h2 className="text-xl font-semibold mb-4">跨链存证系统状态</h2>
          <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
            <div>
              <span className="font-medium">侧链状态: </span>
              <span className={`font-semibold ${sidechainRunning ? 'text-green-600' : 'text-red-600'}`}>
                {sidechainRunning ? '运行中' : '离线'}
              </span>
            </div>
            <div>
              <span className="font-medium">主链状态: </span>
              <span className={`font-semibold ${mainchainRunning ? 'text-green-600' : 'text-red-600'}`}>
                {mainchainRunning ? '运行中' : '离线'}
              </span>
            </div>
            <div>
              <span className="font-medium">当前步骤: </span>
              <span className="text-blue-600 font-semibold">{currentStep}/7</span>
            </div>
            <div>
              <span className="font-medium">存证总数: </span>
              <span className="text-blue-600 font-semibold">{totalEvidences}</span>
            </div>
            <Button onClick={checkServers} variant="secondary" className="text-sm">
              重新检查
            </Button>
          </div>
        </div>

        {/* 流程步骤显示 */}
        <div className="w-full bg-green-50 rounded-lg p-6">
          <h3 className="text-lg font-semibold mb-4">银登数据跨链存证流程</h3>
          <div className="grid grid-cols-1 md:grid-cols-7 gap-2">
            {steps.map((step, index) => (
              <div key={index} className="text-center">
                <div className={`w-8 h-8 rounded-full flex items-center justify-center mx-auto mb-2 font-semibold text-xs ${
                  step.completed ? 'bg-green-500 text-white' : 
                  currentStep === index ? 'bg-blue-500 text-white' : 
                  'bg-gray-300 text-gray-600'
                }`}>
                  {index + 1}
                </div>
                <p className="text-xs font-medium">{step.title}</p>
                <p className="text-xs text-gray-600">{step.description}</p>
              </div>
            ))}
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 w-full">
          {/* 左侧：配置和操作 */}
          <div className="space-y-6">
            {/* 基础配置 */}
            <Card title="基础配置">
              <div className="space-y-4">
                <InputGroup
                  label="存证ID"
                  value={evidenceID}
                  onChange={setEvidenceID}
                  type="text"
                />
                <InputGroup
                  label="客户ID"
                  value={clientID}
                  onChange={setClientID}
                  type="text"
                />
                <InputGroup
                  label="种子值"
                  value={seed.toString()}
                  onChange={(value) => setSeed(parseInt(value) || 123456789)}
                  type="number"
                />
                <InputGroup
                  label="原像值"
                  value={preimage}
                  onChange={setPreimage}
                  type="text"
                />
              </div>
            </Card>

            {/* 银登数据 */}
            <Card title="银登数据">
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">登记数据 (JSON)</label>
                  <textarea
                    value={evidenceData}
                    onChange={async (e) => {
                      setEvidenceData(e.target.value);
                      const hash = await calculateHash(e.target.value);
                      setDataHash(hash);
                    }}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
                    rows={8}
                  />
                </div>
                <div className="bg-gray-50 p-3 rounded">
                  <p className="text-sm text-gray-600 mb-1">数据哈希:</p>
                  <p className="font-mono text-xs break-all">{dataHash}</p>
                  <Button 
                    onClick={async () => {
                      addLog('手动验证哈希计算...');
                      const hash = await verifyHash(evidenceData);
                      setDataHash(hash);
                      addLog(`哈希计算完成: ${hash}`);
                    }}
                    variant="secondary"
                    className="mt-2 text-xs"
                  >
                    验证哈希计算
                  </Button>
                </div>
              </div>
            </Card>

            {/* 锁信息 */}
            <Card title="锁信息">
              <div className="space-y-4">
                <div className="bg-gray-50 p-3 rounded">
                  <p className="text-sm text-gray-600 mb-1">Lock Hash:</p>
                  <p className="font-mono text-xs break-all">{lockHash || '未生成'}</p>
                </div>
                <div className="bg-gray-50 p-3 rounded">
                  <p className="text-sm text-gray-600 mb-1">Lock Key:</p>
                  <p className="font-mono text-xs break-all">{lockKey || '未生成'}</p>
                </div>
              </div>
            </Card>
          </div>

          {/* 右侧：步骤操作 */}
          <div className="space-y-6">
            {/* 步骤1-2 */}
            <Card title="步骤1-2: 初始化与数据提交">
              <div className="space-y-4">
                <Button 
                  onClick={handleInitializeLedgers}
                  disabled={!sidechainRunning || !mainchainRunning || isProcessing}
                  variant="primary"
                  className="w-full"
                >
                  {isProcessing && currentStep === 0 ? '初始化中...' : '初始化账本'}
                </Button>
                
                <Button 
                  onClick={handleSubmitDataToSidechain}
                  disabled={!sidechainRunning || isProcessing || currentStep < 1}
                  variant="primary"
                  className="w-full"
                >
                  {isProcessing && currentStep === 1 ? '提交中...' : '侧链提交数据'}
                </Button>
              </div>
            </Card>

            {/* 步骤3-4 */}
            <Card title="步骤3-4: 创建锁">
              <div className="space-y-4">
                <Button 
                  onClick={handleCreateSidechainLock}
                  disabled={!sidechainRunning || isProcessing || currentStep < 2}
                  variant="success"
                  className="w-full"
                >
                  {isProcessing && currentStep === 2 ? '创建中...' : '侧链创建锁'}
                </Button>
                
                <Button 
                  onClick={handleCreateMainchainLock}
                  disabled={!mainchainRunning || isProcessing || currentStep < 3 || !lockHash}
                  variant="success"
                  className="w-full"
                >
                  {isProcessing && currentStep === 3 ? '创建中...' : '主链创建锁'}
                </Button>
              </div>
            </Card>

            {/* 步骤5-7 */}
            <Card title="步骤5-7: 解锁与同步">
              <div className="space-y-4">
                <Button 
                  onClick={handleUnlockSidechain}
                  disabled={!sidechainRunning || isProcessing || currentStep < 4 || !lockKey}
                  variant="success"
                  className="w-full"
                >
                  {isProcessing && currentStep === 4 ? '解锁中...' : '侧链解锁'}
                </Button>
                
                <Button 
                  onClick={handleUnlockMainchain}
                  disabled={!mainchainRunning || isProcessing || currentStep < 5 || !lockKey}
                  variant="success"
                  className="w-full"
                >
                  {isProcessing && currentStep === 5 ? '解锁中...' : '主链解锁'}
                </Button>
                
                <Button 
                  onClick={handleConfirmSync}
                  disabled={!mainchainRunning || isProcessing || currentStep < 6}
                  variant="success"
                  className="w-full"
                >
                  {isProcessing && currentStep === 6 ? '确认中...' : '确认同步'}
                </Button>
              </div>
            </Card>

            {/* 存证状态 */}
            <Card title={`存证状态 (${totalEvidences}个)`}>
              <div className="max-h-40 overflow-y-auto space-y-2">
                {evidences.length === 0 ? (
                  <p className="text-gray-500 text-center py-4">暂无存证记录</p>
                ) : (
                  evidences.map((evidence, index) => (
                    <div key={index} className="border rounded p-3 bg-gray-50">
                      <div className="flex justify-between items-start mb-2">
                        <span className="font-mono text-sm">{evidence.EvidenceID}</span>
                        <StatusBadge status={evidence.Status === 'SYNCED' ? 'confirmed' : 'pending'} />
                      </div>
                      <div className="text-xs text-gray-600 space-y-1">
                        <p>数据哈希: {evidence.DataHash.slice(0, 16)}...</p>
                        <p>创建时间: {new Date(evidence.CreateTime).toLocaleString()}</p>
                        <p>状态: {evidence.Status}</p>
                      </div>
                    </div>
                  ))
                )}
              </div>
            </Card>
          </div>
        </div>

        {/* 操作日志 */}
        <Card title={`操作日志 (${logs.length}条)`} className="w-full">
          <div className="max-h-60 overflow-y-auto space-y-1">
            {logs.length === 0 ? (
              <p className="text-gray-500 text-center py-4">暂无操作记录</p>
            ) : (
              logs.map((log, index) => (
                <div key={index} className="text-sm font-mono bg-gray-50 p-2 rounded">
                  {log}
                </div>
              ))
            )}
          </div>
          <div className="mt-4 pt-4 border-t">
            <Button 
              onClick={() => setLogs([])} 
              variant="secondary" 
              className="text-sm"
            >
              清空日志
            </Button>
          </div>
        </Card>
      </main>
    </div>
  );
}
